<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="供应商" prop="supplierId">
        <el-select
          v-model="queryParams.supplierId"
          placeholder="请选择供应商"
          filterable
          clearable
          :loading="loadingSuppliers"
          @input="handleSupplierSearch"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="supplier in supplierOptions"
            :key="supplier.id"
            :label="supplier.supplierName"
            :value="supplier.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="120px" label="采购设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入采购设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="采购状态"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.lab_procurement_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lab:procurement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lab:procurement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lab:procurement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lab:procurement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="procurementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column label="采购设备名称" align="center" prop="equipmentName" />
      <el-table-column label="设备类型" align="center" prop="equipmentType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lab_equipment_type" :value="scope.row.equipmentType"/>
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="center" prop="orderDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计到货日期" align="center" prop="arrivalDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购数量" align="center" prop="quantity" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="总价" align="center" prop="totalPrice" />
      <el-table-column label="采购状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lab_procurement_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lab:procurement:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lab:procurement:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="供应商" prop="supplierId">
              <el-select
                v-model="form.supplierId"
                placeholder="请选择供应商"
                filterable
                clearable
                :loading="loadingSuppliers"
                @input="handleSupplierSearch"
              >
                <el-option
                  v-for="supplier in supplierOptions"
                  :key="supplier.id"
                  :label="supplier.supplierName"
                  :value="supplier.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" label="设备类型" prop="equipmentType">
              <el-select v-model="form.equipmentType" placeholder="请选择设备类型">
                <el-option
                  v-for="dict in dict.type.lab_equipment_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label-width="110px" label="采购设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入采购设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label-width="110px" label="订单日期" prop="orderDate">
              <el-date-picker clearable
                              v-model="form.orderDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择订单日期"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label-width="110px" label="预计到货日期" prop="arrivalDate">
              <el-date-picker clearable
                              v-model="form.arrivalDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择预计到货日期"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="采购数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入采购数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" label="单价" prop="unitPrice">
              <el-input v-model="form.unitPrice" placeholder="请输入单价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="总价" prop="totalPrice">
              <el-input v-model="form.totalPrice" placeholder="请输入总价" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProcurement, getProcurement, delProcurement, addProcurement, updateProcurement } from "@/api/lab/procurement";
import {querySupplier} from "@/api/lab/supplier";

export default {
  name: "Procurement",
  dicts: ['lab_equipment_type','lab_procurement_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购表格数据
      procurementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      supplierOptions: [], // 存储供应商列表
      loadingSuppliers: false, // 控制加载状态
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierId: null,
        equipmentName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.loadSupplierOptions(); // 初次加载所有供应商
  },

  methods: {
    /** 查询采购列表 */
    getList() {
      this.loading = true;
      listProcurement(this.queryParams).then(response => {
        this.procurementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    async loadSupplierOptions(query = '') {
      this.loadingSuppliers = true;
      try {
        const response = await querySupplier({ supplierName: query }); // 传递查询条件到API
        this.supplierOptions = response.data.map(item => ({
          id: item.id,
          supplierName: item.supplierName
        }));
      } catch (error) {
        console.error('加载供应商列表失败:', error);
      } finally {
        this.loadingSuppliers = false;
      }
    },
    handleSupplierSearch(query) {
      this.loadSupplierOptions(query); // 根据输入的查询条件加载供应商列表
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        supplierId: null,
        equipmentName: null,
        equipmentType: null,
        orderDate: null,
        arrivalDate: null,
        quantity: null,
        unitPrice: null,
        totalPrice: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProcurement(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProcurement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProcurement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购编号为"' + ids + '"的数据项？').then(function() {
        return delProcurement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lab/procurement/export', {
        ...this.queryParams
      }, `procurement_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
